package enterprise.manage.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;

/**
 * Created by IntelliJ IDEA.
 * User: panxuanang
 * Date: 2010-12-9
 * Time: 10:12:03
 * Desc:
 */
public final class CertCreate {
    /**
     * 构造
     */
    private CertCreate() {
    }

    /**
     * 日志
     */
    public static final Logger LOGGER = LoggerFactory.getLogger(CertCreate.class);
    //版本3普通接口-商户公钥证书物理路径前缀

    /**
     * 对md5摘要进行私钥签名，并进行base64编码
     *
     * @param keystorePath 包含私钥的keystore的文件位置（物理路径）
     * @param md5String    数据的md5摘要
     * @param password     证书密码
     * @param alias        证书别名
     * @return 私钥签名的md5摘要
     */
    public static String privateCertSignBase64(String keystorePath, String md5String, String password, String alias) {
        FileInputStream fis = null;
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS", "SUN");
            fis = new FileInputStream(keystorePath);
            keyStore.load(fis, password.toCharArray());
//            fis.close();
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
            byte[] plainText = md5String.getBytes("UTF-8");
            Signature sig = Signature.getInstance("MD5withRSA"); //SHA1WithRSA
            sig.initSign(privateKey);
            sig.update(plainText);
            byte[] signature = sig.sign();

            return new String(Base64.encode(signature));
        } catch (Exception e) {
            LOGGER.error("error:{}", e);
            return "";
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    LOGGER.error("e={}", e);
                }
            }
        }
    }
}
